<script setup lang="ts">
import { getOrderLogistics } from '@/services/order'
import type { Location, Logisitics } from '@/types/order'
import { onMounted, ref, shallowRef } from 'vue'
import { useRoute } from 'vue-router'
import AMapLoader from '@amap/amap-jsapi-loader'

// 引入图标
import startImg from '@/assets/start.png'
import endImg from '@/assets/end.png'
import carImg from '@/assets/car.png'
// 配置 jscode
window._AMapSecurityConfig = {
  securityJsCode: 'b80860c171f76609afb0148a08747acc'
}
// 获取物流信息
const route = useRoute()
const logistics = ref<Logisitics>()
// 声明 map对象
const map = shallowRef()
// 组件初始化
onMounted(async () => {
  const { data } = await getOrderLogistics(route.params.id as string)
  logistics.value = data
  // 加载地图 实例
  AMapLoader.load({
    key: 'e046c60f8fa1e33e5f03e88c15bf12ee',
    version: '2.0',
    plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.ControlBar', 'AMap.Driving']
  }).then((AMap) => {
    // 使用 AMap 初始化地图
    map.value = new AMap.Map('map', {
      rotateEnable: true,
      pitchEnable: true,
      showBuildingBlock: true, // 楼块
      showIndoorMap: false, // 室内
      showLabel: true, // 标注标签
      /**地图模型 */
      viewMode: '3D',
      /**缩放比例 */
      zoom: 6,
      zooms: [2, 20],
      /** 设置地图样式 */
      mapStyle: 'amap://styles/fresh', //设置地图的显示样式
      setFeatures: ['road', 'point', 'building'],
      rotation: -15
    })
    // 使用地图控件---------------------
    /**比例尺 */
    const scale = new AMap.Scale({
      position: {
        top: '70px',
        left: '20px'
      }
    })
    /**工具条 */
    const toolBar = new AMap.ToolBar({
      position: {
        top: '90px',
        right: '40px'
      }
    })
    const controlBar = new AMap.ControlBar({
      position: {
        top: '190px',
        right: '10px'
      }
    })

    // 通过实例对象调用
    map.value.addControl(scale)
    // map.value.addControl(toolBar) // 方法一
    toolBar.addTo(map.value) // 方法二
    map.value.addControl(controlBar)
    // -------------------------

    //该demo可模拟水印效果
    const layer = new AMap.TileLayer.Flexible({
      cacheSize: 30,
      opacity: 0.3,
      createTile: function (
        x: any,
        y: any,
        z: any,
        success: (arg0: HTMLImageElement) => void,
        fail: () => void
      ) {
        if ((x + y) % 3) {
          fail()
          return
        }

        const img = document.createElement('img')
        img.onload = function () {
          success(img)
        }
        img.crossOrigin = 'anonymous' // 必须添加，同时图片要有跨域头
        img.onerror = function () {
          fail()
        }

        img.src = 'https://a.amap.com/jsapi_demos/static/images/amap.png'
      }
    })
    // 使用 水印效果
    map.value.addLayer(layer)

    // 使用路线规划
    // AMap.plugin(['AMap.Driving'], function () {
    /**初始化路线规划 */
    const driving = new AMap.Driving({
      map: map.value,
      /** 设置实时路况 */
      showTraffic: false,
      /** 隐藏路径规划的起始点图标 */
      hideMarkers: true
    })
    if (
      logistics.value?.logisticsInfo &&
      logistics.value.logisticsInfo.length >= 2
    ) {
      // 解构出 全部坐标的经纬度
      const list = [...logistics.value.logisticsInfo]
      /**创建标记函数:
       * 经纬度
       * 图片遮罩物
       * width
       * height
       */
      const getMarker = (
        point: Location,
        image: string,
        width = 25,
        height = 30
      ) => {
        const icon = new AMap.Icon({
          size: new AMap.Size(width, height),
          image,
          imageSize: new AMap.Size(width, height)
        })
        const marker = new AMap.Marker({
          position: [point.longitude, point.latitude],
          icon,
          offset: new AMap.Pixel(-width / 2, -height)
        })
        return marker
      }

      /**起始坐标 */
      const start = list.shift()
      // 构造起点标记
      const startMarker = getMarker(start!, startImg)
      map.value.add(startMarker)

      /**终点坐标 */
      const end = list.pop()
      // 构造终点标记
      const endMarker = getMarker(end!, endImg)
      map.value.add(endMarker)

      /** 途经点 */
      const waypoints = list.map((item) => [item.longitude, item.latitude])

      /**路线规划:参数1:起始坐标,参数2:终点坐标,参数3:途经点坐标,参数四:回调函数 */
      driving.search(
        [start?.longitude, start?.latitude],
        [end?.longitude, end?.latitude],
        { waypoints },
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        () => {
          // 未出错时，result即是对应的路线规划方案

          // 取出 当前物流经纬度
          const cur = logistics.value?.currentLocationInfo
          // 构造 当前物流经纬度
          const currMarker = getMarker(cur!, carImg, 38, 32)
          map.value.add(currMarker)

          // 3秒后缩放
          setTimeout(() => {
            // setFitView(overlays, immediately, avoid, maxZoom)
            // 根据地图上添加的覆盖物分布情况，自动缩放地图到合适的视野级别，参数均可缺省。
            // overlayList为覆盖物数组，缺省时为当前地图上添加的所有覆盖物图层，
            // immediately代表是否需要动画过程，avoid代表上下左右的像素避让宽度，maxZoom代表fitView之后的最大级
            map.value.setFitView([currMarker], false, [0, 0, 0, 0], 8)
            map.value.setPitch(59)
            // -----------设置楼块----------
            const buildingLayer = new AMap.Buildings({
              zIndex: 130,
              zooms: [16, 20]
            })
            const options = {
              hideWithoutStyle: false, //是否隐藏设定区域外的楼块
              areas: [
                {
                  //围栏1
                  visible: true, //是否可见
                  rejectTexture: false, //是否屏蔽自定义地图的纹理
                  color1: 'ffffff00', //楼顶颜色
                  color2: 'ffffcc00', //楼面颜色
                  path: [
                    [116.473606, 39.995997],
                    [116.473005, 39.995482],
                    [116.472442, 39.994971],
                    [116.472267, 39.994801],
                    [116.471307, 39.995442],
                    [116.471242, 39.995446],
                    [116.471163, 39.995403],
                    [116.4703, 39.994639],
                    [116.469916, 39.994315],
                    [116.469194, 39.993719],
                    [116.469032, 39.993863],
                    [116.468815, 39.994108],
                    [116.468625, 39.994355],
                    [116.468471, 39.99466],
                    [116.468421, 39.994811],
                    [116.468366, 39.995156],
                    [116.468306, 39.996157],
                    [116.468308, 39.996557],
                    [116.468483, 39.996884],
                    [116.468834, 39.997188],
                    [116.469481, 39.997764],
                    [116.470511, 39.998708],
                    [116.471404, 39.999517],
                    [116.471553, 39.999568],
                    [116.471713, 39.999563],
                    [116.471929, 39.999463],
                    [116.473228, 39.998584],
                    [116.474008, 39.998046],
                    [116.474541, 39.997674],
                    [116.474541, 39.997576],
                    [116.474604, 39.997049],
                    [116.474586, 39.996895],
                    [116.474179, 39.996516],
                    [116.473585, 39.995997],
                    [116.473606, 39.995997]
                  ]
                },
                {
                  //围栏2
                  color1: 'ff99ff00',
                  color2: 'ff999900',
                  path: [
                    [116.474609, 39.993478],
                    [116.474489, 39.993495],
                    [116.473693, 39.994009],
                    [116.472898, 39.994546],
                    [116.472837, 39.9946],
                    [116.4728, 39.994653],
                    [116.472779, 39.994745],
                    [116.47282, 39.994815],
                    [116.47491, 39.99655],
                    [116.475041, 39.996607],
                    [116.47525, 39.996643],
                    [116.475715, 39.996686],
                    [116.475947, 39.996688],
                    [116.476103, 39.996658],
                    [116.477228, 39.995932],
                    [116.477261, 39.995833],
                    [116.477264, 39.995729],
                    [116.477205, 39.995625],
                    [116.47642, 39.994899],
                    [116.474854, 39.993558],
                    [116.47469, 39.99348],
                    [116.474609, 39.993478]
                  ]
                }
              ]
            }
            buildingLayer.setStyle(options) //此配色优先级高于自定义mapStyle
            new AMap.Polygon({
              bubble: true,
              fillOpacity: 0.4,
              strokeWeight: 1,
              path: options.areas[0].path,
              map: map
            })
            new AMap.Polygon({
              bubble: true,
              fillColor: 'green',
              fillOpacity: 0.2,
              strokeWeight: 1,
              path: options.areas[1].path,
              map: map
            })
          }, 3000)
        }
      )
    }
    // })
  })
})
</script>

<template>
  <div class="order-logistics-page" v-if="logistics">
    <div id="map">
      <div class="title">
        <van-icon name="arrow-left" @click="$router.back()" />
        <span>{{ logistics.statusValue }}</span>
        <van-icon name="service" />
      </div>
      <div class="current">
        <p class="status">
          {{ logistics.statusValue }} 预计{{ logistics.estimatedTime }}送达
        </p>
        <p class="predict">
          <span>{{ logistics.name }}</span>
          <span>{{ logistics.awbNo }}</span>
        </p>
      </div>
    </div>
    <div class="logistics">
      <p class="title">物流详情</p>
      <van-steps direction="vertical" :active="0">
        <van-step v-for="log in logistics.list" :key="log.id">
          <p class="status">{{ log.statusValue }}</p>
          <p class="content">
            {{ log.content }}
          </p>
          <p class="time">{{ log.createTime }}</p>
        </van-step>
      </van-steps>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.order-logistics-page {
  --van-step-icon-size: 18px;
  --van-step-circle-size: 10px;
}
#map {
  height: 450px;
  background-color: var(--cp-bg);
  overflow: hidden;
  position: relative;
  .title {
    background-color: #fff;
    height: 46px;
    width: 355px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    padding: 0 15px;
    font-size: 16px;
    position: absolute;
    left: 10px;
    top: 10px;
    box-sizing: border-box;
    box-shadow: 0px 0px 22px 0px rgba(229, 229, 229, 0.5);
    z-index: 999;
    > span {
      flex: 1;
      text-align: center;
    }
    .van-icon {
      font-size: 18px;
      color: #666;
      &:last-child {
        color: var(--cp-primary);
      }
    }
  }
  .current {
    height: 80px;
    border-radius: 4px;
    background-color: #fff;
    height: 80px;
    width: 355px;
    box-sizing: border-box;
    padding: 15px;
    position: absolute;
    left: 10px;
    bottom: 10px;
    box-shadow: 0px 0px 22px 0px rgba(229, 229, 229, 0.5);
    z-index: 999;
    .status {
      font-size: 15px;
      line-height: 26px;
    }
    .predict {
      color: var(--cp-tip);
      font-size: 13px;
      margin-top: 5px;
      > span {
        padding-right: 10px;
      }
    }
  }
}
.logistics {
  padding: 0 10px 20px;
  .title {
    font-size: 16px;
    padding: 15px 5px 5px;
  }
  .van-steps {
    :deep(.van-step) {
      &::after {
        display: none;
      }
    }
    .status {
      font-size: 15px;
      color: var(--cp-text3);
      margin-bottom: 4px;
    }
    .content {
      font-size: 13px;
      color: var(--cp-tip);
      margin-bottom: 4px;
    }
    .time {
      font-size: 13px;
      color: var(--cp-tag);
    }
  }
}
</style>
